package com.wifi.base;


import com.wifi.annotation.ShenZhouWifiMethod;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BaseServlet extends HttpServlet {
   Map<String, Method> map;
   @Override
   protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //所有的请求 都会 执行的 方法
      //获取 请求的路径
      String requsetURI=req.getRequestURI();
      String methodName=requsetURI.substring(requsetURI.lastIndexOf("/"));
      Method method=map.get(methodName);

      try{
      if (method!=null){
         method.invoke(this,req,resp);
      }


      } catch (InvocationTargetException e) {
         e.printStackTrace();
      } catch (IllegalAccessException e) {
         e.printStackTrace();
      }
   }
   @Override
   public void init(ServletConfig config) throws ServletException {
      //第一次访问 servlet的时候  service方法调用之前  init 被执行

      //初始化map
   this.map=new ConcurrentHashMap<>();
   Method[] methods =this.getClass().getMethods();
for (Method method:methods){
   ShenZhouWifiMethod shenZhouWifiMethod =method.getAnnotation(ShenZhouWifiMethod.class);
if (shenZhouWifiMethod!=null){
   String url=shenZhouWifiMethod.value();
   map.put(url,method);
}

}
   }

}
